package org.tote.util;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.tote.service.user.CustomUserDetails;
import org.tote.service.user.UserServiceImpl;

public class ToteInterceptor extends HandlerInterceptorAdapter {

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) throws Exception {
		getUserInformation(request);
		super.postHandle(request, response, handler, modelAndView);
	}

	private void getUserInformation(HttpServletRequest request) {
		if (!UserServiceImpl.GUEST_USER.equals(SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal().toString())) {
			CustomUserDetails customUserDetails = (CustomUserDetails) SecurityContextHolder
					.getContext().getAuthentication().getPrincipal();
			if (customUserDetails.getLoggingTime() == null) {
				customUserDetails.setLoggingTime(new Date());
				customUserDetails.setClientIP(getClientIP(request));
				customUserDetails.setClientBrowser(getClientBrowser(request));
			}
		}
	}

	private String getClientBrowser(HttpServletRequest request) {
		//http://user-agent-string.info/
		return request.getHeader("User-Agent");
	}

	private String getClientIP(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			// Get client's IP address
			ip = request.getRemoteAddr(); // 123.123.123.123
			// Get client's hostname
			//String host = request.getRemoteHost(); // hostname.com
		}
		return ip;
	}
}
